// 登录注册页面逻辑
let currentForm = 'login';
let currentUserType = 'user';

// 页面加载时初始化
window.onload = function() {
    initializeAuth();
    checkExistingLogin();
};

// 初始化认证页面
function initializeAuth() {
    // 设置默认表单
    showForm('login');
    
    // 绑定事件监听器
    bindEventListeners();
    
    // 初始化用户类型选择器
    updateUserTypeSelector();
}

// 绑定事件监听器
function bindEventListeners() {
    // 表单切换
    document.getElementById('login-tab').addEventListener('click', () => showForm('login'));
    document.getElementById('register-tab').addEventListener('click', () => showForm('register'));
    
    // 用户类型选择
    document.querySelectorAll('.user-type-btn').forEach(btn => {
        btn.addEventListener('click', (e) => selectUserType(e.target.dataset.type));
    });
    
    // 表单提交
    document.getElementById('login-form').addEventListener('submit', handleLogin);
    document.getElementById('register-form').addEventListener('submit', handleRegister);

        // 密码强度检测
    const passwordInput = document.getElementById('register-password');
    if (passwordInput) {
        passwordInput.addEventListener('input', updatePasswordStrength);
    }
}

// 检查现有登录状态
function checkExistingLogin() {
    const currentUser = localStorage.getItem('currentUser');
    const currentUserType = localStorage.getItem('currentUserType');
    
    if (currentUser && currentUserType) {
        showLoggedInState();
    }
}

// 显示已登录状态
function showLoggedInState() {
    const user = JSON.parse(localStorage.getItem('currentUser'));
    const userType = localStorage.getItem('currentUserType');
    
    document.getElementById('auth-container').innerHTML = `
        <div class="logged-in-state">
            <div class="auth-header">
                <h1 class="auth-title">欢迎回来</h1>
                <p class="auth-subtitle">您已成功登录</p>
            </div>
            <div class="user-info">
                <div class="user-avatar">
                    <span class="avatar-icon">👤</span>
                </div>
                <div class="user-details">
                    <h3>${user.username}</h3>
                    <p>${getUserTypeText(userType)}</p>
                </div>
            </div>
            <div class="action-buttons">
                <button onclick="goToMainPage()" class="action-btn primary">
                    <span class="btn-icon">🏠</span>
                    进入主页面
                </button>
                <button onclick="logout()" class="action-btn secondary">
                    <span class="btn-icon">🚪</span>
                    退出登录
                </button>
            </div>
        </div>
    `;
}

// 显示表单
function showForm(formType) {
    currentForm = formType;
    
    // 更新标签页状态
        document.querySelectorAll('.tab-btn').forEach(btn => btn.classList.remove('active'));
    document.getElementById(formType + '-tab').classList.add('active');
    
    // 显示对应表单
    document.querySelectorAll('.auth-form').forEach(form => form.classList.remove('active'));
    document.getElementById(formType + '-form').classList.add('active');
    
    // 更新用户类型选择器
    updateUserTypeSelector();
    
    // 清除消息
    clearMessages();
}

// 选择用户类型
function selectUserType(userType) {
    currentUserType = userType;
    
    // 更新按钮状态
    document.querySelectorAll('.user-type-btn').forEach(btn => {
        btn.classList.remove('active');
    });
    document.querySelector(`[data-type="${userType}"]`).classList.add('active');
    
    console.log('选择用户类型:', userType);
}

// 更新用户类型选择器
function updateUserTypeSelector() {
    // 确保当前用户类型按钮是激活状态
    document.querySelectorAll('.user-type-btn').forEach(btn => {
        btn.classList.remove('active');
    });
    const activeBtn = document.querySelector(`[data-type="${currentUserType}"]`);
    if (activeBtn) {
        activeBtn.classList.add('active');
    }
}

// 处理登录
function handleLogin(e) {
    e.preventDefault();
    
    const username = document.getElementById('login-username').value.trim();
    const password = document.getElementById('login-password').value;
    
    // 基本验证
    if (!username || !password) {
        showMessage('请填写完整的登录信息', 'error');
        return;
    }

        // 显示加载状态
    setLoadingState('login', true);
    
    // 模拟登录验证
    setTimeout(() => {
        const user = authenticateUser(username, password, currentUserType);
            
            if (user) {
            // 登录成功
                localStorage.setItem('currentUser', JSON.stringify(user));
            localStorage.setItem('currentUserType', currentUserType);
                
            showMessage('登录成功！', 'success');
                
            // 延迟跳转
                setTimeout(() => {
                goToMainPage();
            }, 1000);
            } else {
            showMessage('用户名或密码错误', 'error');
        }
        
        setLoadingState('login', false);
    }, 1000);
}

// 处理注册
function handleRegister(e) {
    e.preventDefault();
    
    const username = document.getElementById('register-username').value.trim();
    const password = document.getElementById('register-password').value;
    const confirmPassword = document.getElementById('register-confirm-password').value;
    const phone = document.getElementById('register-phone').value.trim();
    
    console.log('注册信息:', { username, password, confirmPassword, phone, userType: currentUserType });
    
    // 基本验证
    if (!username || !password || !confirmPassword || !phone) {
        showMessage('请填写完整的注册信息', 'error');
        return;
    }
        
        if (password !== confirmPassword) {
        showMessage('两次输入的密码不一致', 'error');
            return;
        }

    if (password.length < 4) {
        showMessage('密码长度至少4位', 'error');
            return;
        }

    // 手机号验证（简化版）
    if (!/^(\+?\d{7,15}|\d{11})$/.test(phone)) {
        showMessage('请输入有效的手机号', 'error');
                return;
            }

    // 显示加载状态
    setLoadingState('register', true);
            
    // 模拟注册过程
    setTimeout(() => {
        const result = registerUser(username, password, phone, currentUserType);
            
        if (result.success) {
            showMessage('注册成功！', 'success');
            
            // 自动登录
            setTimeout(() => {
                localStorage.setItem('currentUser', JSON.stringify(result.user));
                localStorage.setItem('currentUserType', currentUserType);
                goToMainPage();
            }, 1000);
        } else {
            showMessage(result.message, 'error');
        }
        
        setLoadingState('register', false);
    }, 1000);
}

// 用户认证（调用后端）
async function authenticateUser(username, password, userType) {
    try {
        const res = await fetch('http://localhost:8080/api/auth/login', {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify({ username, password, userType })
        });
        if (!res.ok) return null;
        const data = await res.json();
        return {
            id: data.id,
            username: data.username,
            phone: data.phone,
            userType: data.type,
            registerTime: data.registerTime
        };
    } catch (e) {
        return null;
    }
}

// 用户注册（调用后端）
async function registerUser(username, password, phone, userType) {
    try {
        const res = await fetch('http://localhost:8080/api/auth/register', {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify({ username, password, phone, type: userType })
        });
        if (!res.ok) {
            const err = await res.json().catch(() => ({}));
            return { success: false, message: err.message || '注册失败' };
        }
        const data = await res.json();
        return {
            success: true,
            user: {
                id: data.id,
                username: data.username,
                phone: data.phone,
                userType: data.type,
                registerTime: data.registerTime
            }
        };
    } catch (e) {
        return { success: false, message: '网络错误' };
    }
}

// 获取下一个用户ID
function getNextUserId() {
    const users = getUsersFromStorage();
    if (users.length === 0) return 1;
    return Math.max(...users.map(u => u.id)) + 1;
}

// 从本地存储获取用户
function getUsersFromStorage() {
    const users = localStorage.getItem('users');
    return users ? JSON.parse(users) : [];
}

// 更新密码强度
function updatePasswordStrength() {
    const password = document.getElementById('register-password').value;
    const strength = calculatePasswordStrength(password);
    
    const strengthBar = document.querySelector('.strength-bar');
    const strengthText = document.querySelector('.strength-text');
    
    if (strengthBar && strengthText) {
        strengthBar.className = `strength-bar strength-${strength.level}`;
        strengthBar.style.width = strength.percentage + '%';
        strengthText.textContent = strength.text;
    }
}

// 计算密码强度
function calculatePasswordStrength(password) {
    if (password.length < 4) {
        return { level: 'weak', percentage: 33, text: '密码太短' };
    }
    
        let score = 0;
        if (password.length >= 6) score++;
        if (/[a-z]/.test(password)) score++;
        if (/[A-Z]/.test(password)) score++;
        if (/[0-9]/.test(password)) score++;
        if (/[^A-Za-z0-9]/.test(password)) score++;
        
    if (score < 2) {
        return { level: 'weak', percentage: 33, text: '密码强度：弱' };
    } else if (score < 4) {
        return { level: 'medium', percentage: 66, text: '密码强度：中等' };
    } else {
        return { level: 'strong', percentage: 100, text: '密码强度：强' };
    }
}

// 设置加载状态
function setLoadingState(formType, isLoading) {
    const submitBtn = document.querySelector(`#${formType}-form .submit-btn`);
    const originalText = submitBtn.textContent;
    
    if (isLoading) {
        submitBtn.disabled = true;
        submitBtn.innerHTML = '<span class="loading"></span> 处理中...';
    } else {
        submitBtn.disabled = false;
        submitBtn.textContent = originalText;
    }
}

// 显示消息
function showMessage(message, type) {
    clearMessages();
    
        const messageDiv = document.createElement('div');
    messageDiv.className = `message ${type}-message`;
        messageDiv.textContent = message;

    const activeForm = document.querySelector('.auth-form.active');
    activeForm.insertBefore(messageDiv, activeForm.firstChild);

    // 自动隐藏成功消息
    if (type === 'success') {
        setTimeout(() => {
                messageDiv.remove();
        }, 3000);
    }
}

// 清除消息
function clearMessages() {
    document.querySelectorAll('.message').forEach(msg => msg.remove());
}

// 跳转到主页面
function goToMainPage() {
    window.location.href = 'simple-index.html';
}

// 退出登录
function logout() {
        localStorage.removeItem('currentUser');
        localStorage.removeItem('currentUserType');
    location.reload();
}

// 获取用户类型文本
function getUserTypeText(userType) {
    const types = {
        'user': '普通用户',
        'merchant': '商家',
        'rider': '骑手'
    };
    return types[userType] || '未知';
}

// 初始化测试用户（如果不存在）
function initializeTestUsers() {
    const users = getUsersFromStorage();
    if (users.length === 0) {
        const testUsers = [
            {
                id: 1,
                username: 'testuser',
                password: '1234',
                phone: '13800138000',
                userType: 'user',
                registerTime: new Date().toLocaleString()
            },
            {
                id: 2,
                username: 'testmerchant',
                password: '1234',
                phone: '13800138001',
                userType: 'merchant',
                registerTime: new Date().toLocaleString()
            },
            {
                id: 3,
                username: 'testrider',
                password: '1234',
                phone: '13800138002',
                userType: 'rider',
                registerTime: new Date().toLocaleString()
            }
        ];
        
        localStorage.setItem('users', JSON.stringify(testUsers));
    }
}

// 页面加载时初始化测试用户
initializeTestUsers();
